<template>
  <div>
    <div id="baidu-map-container" style="width: 100%; height: 650px;"></div>
    <el-dialog
      v-model="visible"
      title="拍照上传"
      width="1065px"
      @close="onCancel"
    >
      <div class="box">
        <video id="videoCamera" class="canvas" :width="videoWidth" :height="videoHeight" autoplay></video>
        <canvas id="canvasCamera" class="canvas" :width="videoWidth" :height="videoHeight"></canvas>
      </div>
      <template #footer>
        <el-button @click="drawImage" :icon="Camera" size="small">拍照</el-button>
        <el-button v-if="os" @click="getCompetence" :icon="VideoCamera" size="small">打开摄像头</el-button>
        <el-button v-else @click="stopNavigator" :icon="SwitchButton" size="small">关闭摄像头</el-button>
        <el-button @click="resetCanvas" :icon="Refresh" size="small">重置</el-button>
        <el-button @click="onCancel" :icon="CircleClose" size="small">完成</el-button>
      </template>
    </el-dialog>
  </div>
</template>


<script setup>
import { ref, onMounted, nextTick } from 'vue';
import { ElNotification } from 'element-plus';
import { Camera, VideoCamera, SwitchButton, Refresh, CircleClose } from '@element-plus/icons-vue';

const visible = ref(false);
const os = ref(false);
const thisVideo = ref(null);
const thisContext = ref(null);
const thisCancas = ref(null);
const videoWidth = ref(500);
const videoHeight = ref(400);
const imgSrc = ref("");

function initMap() {
  if (!window.BMapGL) {
    console.error('百度地图API未加载');
    return;
  }
  const map = new BMapGL.Map('baidu-map-container');
map.centerAndZoom(new BMapGL.Point(115.826725, 39.069073), 19);
map.enableScrollWheelZoom(true);
const markers = [
  { lat: 39.068673, lng: 115.826125, title: '垃圾桶1' },   // 原lat-0.0002，下同
  { lat: 39.068473, lng: 115.826325, title: '垃圾桶2' },
  { lat: 39.068373, lng: 115.825925, title: '垃圾桶4' },
  { lat: 39.068773, lng: 115.826525, title: '垃圾桶5' },
  { lat: 39.068573, lng: 115.826725, title: '垃圾桶6' },
  { lat: 39.068273, lng: 115.826225, title: '垃圾桶7' },
  { lat: 39.068473, lng: 115.825625, title: '垃圾桶8' },
  { lat: 39.068873, lng: 115.826025, title: '垃圾桶10' },
  { lat: 39.068673, lng: 115.827025, title: '垃圾桶16' },
  { lat: 39.068373, lng: 115.826625, title: '垃圾桶17' },
  { lat: 39.068773, lng: 115.825825, title: '垃圾桶18' },
  { lat: 39.068573, lng: 115.826425, title: '垃圾桶19' },
  { lat: 39.068973, lng: 115.826225, title: '垃圾桶21' },
  { lat: 39.068473, lng: 115.826925, title: '垃圾桶22' },
  { lat: 39.068373, lng: 115.825725, title: '垃圾桶24' },
  { lat: 39.068673, lng: 115.826325, title: '垃圾桶25' },
  { lat: 39.068573, lng: 115.825925, title: '垃圾桶26' },
  { lat: 39.068773, lng: 115.826625, title: '垃圾桶27' },
  { lat: 39.068473, lng: 115.827225, title: '垃圾桶28' },
  { lat: 39.068273, lng: 115.826525, title: '垃圾桶30' },
  { lat: 39.068873, lng: 115.825725, title: '垃圾桶31' },
  { lat: 39.068573, lng: 115.827125, title: '垃圾桶32' },
  { lat: 39.068373, lng: 115.826125, title: '垃圾桶34' },
  { lat: 39.068673, lng: 115.826825, title: '垃圾桶35' }
];
  markers.forEach(markerData => {
    const marker = new BMapGL.Marker(new BMapGL.Point(markerData.lng, markerData.lat));
    map.addOverlay(marker);
    var infoWindow = new BMapGL.InfoWindow(`地址：雄安新区紫云东园${markerData.title}`, {
      width: 200,
      height: 100,
      title: '垃圾桶信息'
    });
    marker.addEventListener('click', function () {
      map.openInfoWindow(infoWindow, marker.getPosition());
    });
  });
const monitorMarkers = [
  { lat: 39.068873, lng: 115.826225, title: '监控1' },   // 左下区域偏北
  { lat: 39.068673, lng: 115.825925, title: '监控2' },   // 左下核心区（左下方明显）
  { lat: 39.068973, lng: 115.826525, title: '监控3' },   // 左下区域偏东
  { lat: 39.068773, lng: 115.825625, title: '监控4' },   // 左下区域偏西
  { lat: 39.068573, lng: 115.826125, title: '监控5' },   // 左下区域中部
  { lat: 39.068273, lng: 115.826325, title: '监控6' },   // 左下区域最南侧
  { lat: 39.068973, lng: 115.826025, title: '监控7' },   // 与监控1对称分布
  { lat: 39.068473, lng: 115.825425, title: '监控8' },   // 左下区域最西侧
  { lat: 39.068873, lng: 115.827025, title: '监控9' },   // 左下区域偏东（未超经度上限）
  { lat: 39.068373, lng: 115.826425, title: '监控11' },  // 左下区域偏南
  { lat: 39.068273, lng: 115.826625, title: '监控12' },  // 左下区域偏南（保留原重复逻辑）
  { lat: 39.068273, lng: 115.826625, title: '监控13' },  // 与监控12重叠（同原数据设计）
  { lat: 39.069073, lng: 115.825825, title: '监控14' },  // 左下区域偏北（贴近纬度上限）
  { lat: 39.068973, lng: 115.826325, title: '监控15' }   // 左下区域中部偏北
];
  monitorMarkers.forEach(markerData => {
    const marker = new BMapGL.Marker(new BMapGL.Point(markerData.lng, markerData.lat));
    map.addOverlay(marker);
    var infoWindowContent = `
      <div>
        <p>地址：雄安新区紫云东园${markerData.title}</p>
        <button class="button" onclick="window.onTake()">查看详情（播放视频）</button>
      </div>
    `;
    var infoWindow = new BMapGL.InfoWindow(infoWindowContent, {
      width: 200,
      height: 150,
      title: '查看监控'
    });
    marker.addEventListener('click', function () {
      map.openInfoWindow(infoWindow, marker.getPosition());
    });
  });
}

function onTake() {
  visible.value = true;
  getCompetence();
}

function onCancel() {
  visible.value = false;
  stopNavigator();
}

function getCompetence() {
  nextTick(() => {
    os.value = false;
    thisCancas.value = document.getElementById('canvasCamera');
    thisContext.value = thisCancas.value.getContext('2d');
    thisVideo.value = document.getElementById('videoCamera');
    if (navigator.mediaDevices === undefined) {
      navigator.mediaDevices = {};
    }
    if (navigator.mediaDevices.getUserMedia === undefined) {
      navigator.mediaDevices.getUserMedia = function (constraints) {
        let getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.getUserMedia;
        if (!getUserMedia) {
          return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
        }
        return new Promise(function (resolve, reject) {
          getUserMedia.call(navigator, constraints, resolve, reject);
        });
      };
    }
    const constraints = {
      audio: false,
      video: { width: videoWidth.value, height: videoHeight.value, transform: 'scaleX(-1)' }
    };
    navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
      if ('srcObject' in thisVideo.value) {
        thisVideo.value.srcObject = stream;
      } else {
        thisVideo.value.src = window.URL.createObjectURL(stream);
      }
      thisVideo.value.onloadedmetadata = function () {
        thisVideo.value.play();
      };
    }).catch(err => {
      ElNotification({
        title: '警告',
        message: '没有开启摄像头权限或浏览器版本不兼容.',
        type: 'warning'
      });
    });
  });
}

function drawImage() {
  thisContext.value.drawImage(thisVideo.value, 0, 0, videoWidth.value, videoHeight.value);
  imgSrc.value = thisCancas.value.toDataURL('image/png');
}

function clearCanvas(id) {
  let c = document.getElementById(id);
  let cxt = c.getContext('2d');
  cxt.clearRect(0, 0, c.width, c.height);
}

function resetCanvas() {
  imgSrc.value = '';
  clearCanvas('canvasCamera');
}

function stopNavigator() {
  if (thisVideo.value && thisVideo.value.srcObject) {
    thisVideo.value.srcObject.getTracks()[0].stop();
    os.value = true;
  }
}

onMounted(() => {
  initMap();
  window.onTake = onTake;
});
</script>

<style scoped>
</style>
